package ic

import (
	"bytes"
	"fmt"
	"image"

	"golang.org/x/image/tiff"
)

type TIFFConverter struct{}

func (t *TIFFConverter) SupportedFormat() string {
	return "TIFF"
}

func (t *TIFFConverter) FileExtension() string {
	return ".tiff"
}

func (t *TIFFConverter) MimeType() string {
	return "image/tiff"
}

func (t *TIFFConverter) Encode(img image.Image, options ...Options) ([]byte, error) {
	var buf bytes.Buffer

	// 合并选项
	opts := MergeOptions(options...)

	// TIFF根据质量选择压缩方式
	compression := tiff.Deflate
	if opts.Lossless {
		compression = tiff.Uncompressed
	} else if opts.Quality > 90 {
		compression = tiff.LZW
	}

	tiffOptions := &tiff.Options{
		Compression: compression,
	}

	if err := tiff.Encode(&buf, img, tiffOptions); err != nil {
		return nil, fmt.Errorf("TIFF编码失败: %v", err)
	}

	return buf.Bytes(), nil
}

func (t *TIFFConverter) Decode(data []byte) (image.Image, error) {
	return tiff.Decode(bytes.NewReader(data))
}
